package org.wei.p2p.account.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.wei.p2p.account.common.constant.AccountErrorCode;
import org.wei.p2p.account.service.SmsService;
import org.wei.p2p.api.account.model.VerificationInfoDTO;
import org.wei.p2p.common.domain.BusinessException;
import org.wei.p2p.common.domain.CommonErrorCode;
import org.wei.p2p.common.domain.RestResponse;
import org.wei.p2p.common.utils.OkHttpUtil;

/**
 * @author wei
 * @date 2022/4/21 16:34
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Value("${sms.url}")
    private String smsUrl;

    @Value("${sms.enable}")
    private Boolean smsEnable;


    @Override
    public VerificationInfoDTO getSmsCode(String mobile) {
        if (smsEnable) {
            String data = OkHttpUtil.post(smsUrl + "/generate?effectiveTime=300&name=sms", "{\"mobile\":" + mobile + "}");
            RestResponse restResponse = JSONObject.parseObject(data, RestResponse.class);
            return JSONObject.parseObject(restResponse.getResult().toString(), VerificationInfoDTO.class);
        }
        return new VerificationInfoDTO();
    }

    /**
     * 校验验证码
     * @param key 校验标识 redis中的键
     * @param code 短信验证码
     */
    @Override
    public void verifySmsCode(String key, String code) {
        if (smsEnable) {
            StringBuilder params = new StringBuilder("/verify?name=sms");
            params.append("&verificationKey=").append(key);
            params.append("&verificationCode=").append(code);
            String data = OkHttpUtil.post(smsUrl + params, "");
            RestResponse smsResponse = JSONObject.parseObject(data, RestResponse.class);
            if (smsResponse.getCode() != CommonErrorCode.SUCCESS.getCode() ||
                    "false".equalsIgnoreCase(smsResponse.getResult().toString())) {
                throw new BusinessException(AccountErrorCode.E_140152);
            }
        }
    }

}
